import url from 'url';
import router from 'koa-router';
import DBConnectTool from '../com/DBTool/DBConnectTool';
import ContentTypeTool from '../lib/ContentTypeTool';

const DBRoutes = new router({prefix: '/DBService'});

// 通配符的写法
DBRoutes
	.get('/(.*)', async (ctx: any) => {
		let reqUrl = ctx.request.url.replace('/DBService/', '');
		let urlObj = url.parse(reqUrl, true) as any;
		// let query = urlObj.query;
		reqUrl = decodeURI(urlObj.pathname);

		let pathItem = reqUrl.split('/');

		if (pathItem?.length) {
			let DBName = pathItem.shift();
			let fullPath = '/' + pathItem.join('/');

			let file;
			let dbTool = await DBConnectTool.openDB(DBName);

			if (dbTool) {

				if (DBName.endsWith('-Index')) {
					const indexDB = await DBConnectTool.openDB(DBName);
					const indexInfo = await indexDB.getFileByFullPath(fullPath, false);
					const md5 = indexInfo?.file_md5;
					if (md5) {
						const dataDBName = DBName.endsWith('-16x16-Index') ? DBName.replace('-16x16-Index', '-') : DBName.replace('-Index', '-');
						const dbTool = await DBConnectTool.openDB(dataDBName + md5.substring(0, DBName.endsWith('-16x16-Index') ? 2 : 1));
						file = await dbTool.getFileByFullPath(fullPath, false);
					}
				} else {
					file = await dbTool.getFileByFullPath(fullPath, false);
				}

				if (!file || !file.file_data) {
					ctx.status = 422;
					ctx.set('Content-Type', 'application/json;charset=utf-8');
					ctx.body = JSON.stringify({message: `资源库【${DBName}】连接成功，但找不到该文件资源，路径：【${fullPath}】`});
				} else {
					let contentType = ContentTypeTool.getContentType(file.file_name);
					file.file_zip === 'gzip' && (ctx.set('Content-Encoding', 'gzip'));
					ctx.set('Content-Type', contentType);
					ctx.body = file.file_data;
				}
			} else {
				ctx.status = 422;
				ctx.set('Content-Type', 'application/json;charset=utf-8');
				ctx.body = JSON.stringify({message: `资源库不存在【${DBName}】，请检查 Url`});
				return;
			}
		}
	})
;


export default DBRoutes;
